package day04.checkCode;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CheckCode
{
    private static String coder = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ你好我是大的生发生解了看人家顺丰三大六块腹肌安师大";
    private static CheckCode checkCode;
    //定义一个变量用于存储验证码
    private static String coderStr = "";
    private CheckCode()
    {

    }

    public static CheckCode getInstance()
    {
        if(checkCode == null)
        {
            checkCode = new CheckCode();
            return  checkCode;
        }

        return checkCode;
    }

    /**
     * 获取产生的验证码
     * @return
     */
    public String getCoderStr()
    {
        return coderStr;
    }

    /**
     * 随机产生颜色(红绿蓝三基色产生随机颜色)
     * @return
     */
    public Color getRandomColor(int c,int r)
    {
        Random random = new Random();
        //先判断传递进来的指定值是否大于255,如果大于255,则直接指定为255
        if(c > 255)
        {
            c = 255;
        }

        if(r > 255)
        {
            r = 255;
        }
        //如果不大于255,则产生三个颜色
        int red = c + random.nextInt(r-c);
        int green = c + random.nextInt(r-c);
        int blue = c + random.nextInt(r-c);

        return new Color(red,green,blue);

    }

    /**
     * 随机产生验证码图片
     * 图片中包含有验证码和随机线段
     * @return
     */
    public BufferedImage getBufferedImage()
    {
        //指定图片的大小
        int width = 100;
        int height = 100;

        Random random = new Random();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(getRandomColor(200,250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("宋体", Font.BOLD, 18));
        g.setColor(getRandomColor(160,200));
        //随机画线段
        for (int i = 0; i < 10; i++)
        {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt();
            int yl = random.nextInt();
            g.drawLine(x, y, x + xl, y + yl);
        }

        //随机产生几个验证码,此处产生4个验证码
        for (int i = 0; i < 4; i++)
        {
            String yzm = String.valueOf(coder.charAt(random.nextInt(coder.length())));
            coderStr+=yzm;
            g.setColor(new Color(20+random.nextInt(235),20+random.nextInt(235),20+random.nextInt(235)));
            g.drawString(yzm,13*i+6,26);
        }

        return image;

    }


    public static void main(String[] args)
    {
        CheckCode checkCode = new CheckCode();
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        frame.add(new JLabel(new ImageIcon(checkCode.getBufferedImage())));
        frame.setVisible(true);
        frame.setSize(300,300);
        frame.setLocation(200,200);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


}
